package com.mkz.order.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mkz.order.entity.Order;
import com.mkz.order.mapper.OrderMapper;
import com.mkz.order.service.OrderService;
import com.mkz.storage.feign.StorageClient;

import io.seata.spring.annotation.GlobalTransactional;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 订单表
 *
 * @author KuangJianyu
 * @date 2020-05-06 13:47:00
 */
@Slf4j
@Service
@AllArgsConstructor
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements OrderService {
	private final StorageClient storageClient;
	
	@Override
	@GlobalTransactional
	@Transactional(rollbackFor = Exception.class)
	public boolean createOrder(String userId, String commodityCode, Integer count) {
		int maxCount = 100;
		Integer orderMoney = count * 5;
		Order order = new Order()
			.setUserId(userId)
			.setCommodityCode(commodityCode)
			.setCount(count)
			.setMoney(orderMoney);
		int cnt1 = baseMapper.insert(order);
		boolean sresult = storageClient.deduct(commodityCode, count).getData();
		if (sresult) {
			log.error("创建订单失败");
		} else if (count > maxCount) {
			log.error("超过订单最大值，创建订单失败");
		}
		return cnt1 > 0 && sresult;
	}
}
